package com.xingkeduo.business.transformation.json;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.pojo.query.ConsumerStatisticsQO;
import com.xingkeduo.pojo.table.ConsumerStatisticsTO;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.domain.Page;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;
import com.xingkeduo.util.tool.RegularUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @Description:
 * @Author:gaozifeng
 * @Date 2019/2/20 10:21
 **/
@Component
public class ConsumerStatisticsJTO extends BaseJson {

    private static String ids = "ids";

    /**
     * 新增
     *
     * @param json:
     * @return : com.xingkeduo.pojo.table.ConsumerStatisticsTO
     * @author : gaozifeng
     * @date : 2019/3/14 17:53
     */
    public static ConsumerStatisticsTO createTableForNew(String json) throws Throwable {
        ConsumerStatisticsTO table = new ConsumerStatisticsTO();
        JsonNode root = validJson(json);
        if (root == null) {
            throw new InputParamException(InputParamException.Type.INVALID, "参数");
        }
        table.setId(validId(root, YesNoEnum.YES)).setServiceTotal(validTotal(root, YesNoEnum.NO)).setServiceMoney(validServiceMoney(root, YesNoEnum.NO))
                .setLastTime(validLastTime(root, YesNoEnum.NO)).setRefundMoney(validRefundMoney(root, YesNoEnum.NO));
        return table;
    }


    /**
     * 修改
     *
     * @param json:
     * @return : com.xingkeduo.pojo.table.ConsumerStatisticsTO
     * @author : gaozifeng
     * @date : 2019/3/14 17:52
     */
    public static ConsumerStatisticsTO createTableForModify(String json) throws Throwable {
        ConsumerStatisticsTO table = new ConsumerStatisticsTO();
        JsonNode root = validJson(json);
        if (root == null)
            throw new InputParamException(InputParamException.Type.INVALID, "参数");
        table.setServiceTotal(validTotal(root, YesNoEnum.NO)).setServiceMoney(validServiceMoney(root, YesNoEnum.NO)).setId(validId(root, YesNoEnum.YES));
        return table;
    }


    /**
     * 校验id
     *
     * @param json:
     * @return : com.xingkeduo.pojo.table.ConsumerStatisticsTO
     * @author : gaozifeng
     * @date : 2019/3/14 17:52
     */
    public static ConsumerStatisticsQO createQueryForPrimary(String json) throws Throwable {
        ConsumerStatisticsQO query = new ConsumerStatisticsQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;

        query.setId(validId(root, YesNoEnum.NO));

        if (root.has(ids)) {
            if (!root.path(ids).isArray()) {
                throw new InputParamException(InputParamException.Type.INVALID, "用户集合");
            } else {
                List<Long> list = new LinkedList<>();
                JsonNode nodeIds = root.path(ids);
                nodeIds.forEach((JsonNode node) -> {
                    list.add(Long.parseLong(String.valueOf(node)));
                });
                query.setIds(list);
            }
        }

        return query;
    }

    /**
     * 入参json
     *
     * @param json:
     * @return : com.xingkeduo.pojo.query.ConsumerQO
     * @author : gaozifeng
     * @date : 2019/2/28 11:00
     */
    public static ConsumerStatisticsQO createQueryConditionByTotal(String json) throws Throwable {
        ConsumerStatisticsQO query = new ConsumerStatisticsQO();
        JsonNode root = validJson(json);
        if (root == null)
            return query;
        //根据前端传1 2 3 来定义范围
        if (root.has("servicetotal")) {
            Integer total = Integer.valueOf(root.path("servicetotal").asText().trim());
            switch (total) {
                case 0:
                    query.setServiceTotalmin(0);
                    query.setServiceTotal(3);
                    break;
                case 1:
                    query.setServiceTotalmin(4);
                    query.setServiceTotal(6);
                    break;
                case 2:
                    query.setServiceTotalmin(6);
                    query.setServiceTotal(10);
                    break;
                case 3:
                    query.setServiceTotalmin(11);
                    query.setServiceTotal(20);
                    break;
                case 4:
                    query.setServiceTotalmin(21);
                    query.setServiceTotal(-1);
                    break;
                case -1:
                    break;
            }
        }
        return query;
    }


    /**
     * 返回实体信息
     *
     * @param table:
     * @return : com.fasterxml.jackson.databind.node.ObjectNode
     * @author : gaozifeng
     * @date : 2019/2/19 16:24
     */
    public static ObjectNode toJson(ConsumerStatisticsTO table) throws Throwable {
        ObjectNode root = MAPPER.createObjectNode();
        SimpleDateFormat formatTimestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (table != null) {
            root.put("id", table.getId());
            root.put("code", table.getCode());
            if (table.getServiceTotal() > 0) {
                root.put("serviceTotal", table.getServiceTotal());
                root.put("servicemoney", table.getServiceMoney());
            }
            if (table.getIsDelete() != null) {
                root.put("isdelete_value", table.getIsDelete().getValue());
                root.put("isdelete_desc", table.getIsDelete().getDesc());
            }
            root.put("createdBy", table.getCreatedBy());
            if (table.getCreatedTime() != null) {
                root.put("createdTime", formatTimestamp.format(table.getCreatedTime()));
            }
            if (null != table.getRefundMoney()) {
                root.put("refundMoney", table.getRefundMoney());
            }
            if (null != table.getLastTime()) {
                root.put("lastTime", formatTimestamp.format(table.getLastTime()));
            }
            root.put("updatedBy", table.getUpdatedBy());
            if (table.getUpdatedTime() != null) {
                root.put("updatedTime", formatTimestamp.format(table.getUpdatedTime()));
            }
        }

        return root;
    }

    /**
     * 返回集合
     *
     * @param tables:
     * @return : com.fasterxml.jackson.databind.node.ArrayNode
     * @author : gaozifeng
     * @date : 2019/2/19 16:25
     */
    public static ArrayNode toJson(List<ConsumerStatisticsTO> tables) throws Throwable {
        ArrayNode root = MAPPER.createArrayNode();

        if (!CommonUtil.isEmpty(tables)) {
            for (Iterator<ConsumerStatisticsTO> iterator = tables.iterator(); iterator.hasNext(); ) {
                root.add(toJson(iterator.next()));
            }
        }
        return root;
    }

    public static ObjectNode toJsonPage(Page<ConsumerStatisticsTO> page) throws Throwable {
        ObjectNode root = MAPPER.createObjectNode();
        if (page != null) {
            root.put("pageNo", page.getPageNo());
            root.put("pageSize", page.getPageSize());
            root.put("pageTotal", page.getPageTotal());
            root.put("recordTotal", page.getRecordTotal());
            root.put("dtoLists", toJson(page.getDtoList()));
        }
        return root;
    }

    /**
     * 验证服务次数
     *
     * @param node:
     * @param isRequired:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019/2/19 16:25
     */
    public static int validTotal(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "serviceTotal";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);

        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (StringUtils.isEmpty(value) || value.length() > 10)
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            return Integer.valueOf(value);
        }
        return 0;
    }

    /**
     * 服务金额
     *
     * @param node:
     * @param isRequired:
     * @return : java.lang.String
     * @author : gaozifeng
     * @date : 2019年3月14日17:01:30
     */
    public static BigDecimal validServiceMoney(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "serviceMoney";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);
        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (StringUtils.isEmpty(value)) {
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            }
            BigDecimal bd = new BigDecimal(value);
            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            return bd;
        }
        return null;
    }

    /**
     * 退款金额
     *
     * @param node:
     * @param isRequired:
     * @return : java.math.BigDecimal
     * @author : gaozifeng
     * @date : 2019/6/5 10:47
     */
    public static BigDecimal validRefundMoney(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "refundMoney";
        if (YesNoEnum.YES == isRequired && !node.has(key))
            throw new InputParamException(InputParamException.Type.NULL, key);
        if (node.has(key)) {
            String value = node.path(key).asText().trim();
            if (StringUtils.isEmpty(value)) {
                throw new InputParamException(InputParamException.Type.INVALID, key + " error");
            }
            BigDecimal bd = new BigDecimal(value);
            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
            return bd;
        }
        return null;
    }

    public static Date validLastTime(JsonNode node, YesNoEnum isRequired) throws Throwable {
        String key = "lastTime";
        if (YesNoEnum.YES == isRequired && !node.has(key)) {
            throw new InputParamException(InputParamException.Type.NULL, key);
        }
        try {
            if (node.has(key)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                String value = node.path(key).asText().trim();
                if (null != value) {
                    Date date = null;
                    if (RegularUtil.isPositiveInteger(value)) {
                        Long longTime = new Long(value);
                        String formatTime = sdf.format(longTime);
                        date = sdf.parse(formatTime);
                    } else {
                        date = sdf.parse(value);
                    }
                    if (date == null) {
                        throw new InputParamException(InputParamException.Type.INVALID, key + " error");
                    }
                    return date;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
